package mathive.client.panels;

import mathive.client.PanelHandler;
import mathive.client.UserService;
import mathive.client.UserServiceAsync;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class RegisterPanel {
	private static final UserServiceAsync SERVICE = GWT.create(UserService.class);

	private VerticalPanel mainPanel = new VerticalPanel();
	private TextBox username = new TextBox();
	private PasswordTextBox password = new PasswordTextBox();
	private TextBox email = new TextBox();
	private Label user_label = new Label("Username");
	private Label pass_label = new Label("Password");
	private Label email_label = new Label("E-mail");
	private Button registerButton = new Button("Register");
	
	public RegisterPanel(){
		
		// Listen for mouse events on the register button.
		registerButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				SERVICE.registerOnServer(
						username.getText(),
						password.getText(),
						email.getText(), new 
						RegisterResponse());
			}
		});
		
		initialize();
	}
	
	public Widget getPanel(){
		mainPanel.clear();
		initialize();
		return mainPanel;
	}
	
	private void initialize(){		
		
		mainPanel.add(new HTML("<h1>Register</h1>"));
		mainPanel.add(user_label);
		mainPanel.add(username);
		mainPanel.add(pass_label);
		mainPanel.add(password);
		mainPanel.add(email_label);
		mainPanel.add(email);
		mainPanel.add(registerButton);
		mainPanel.setCellHorizontalAlignment(registerButton, HasHorizontalAlignment.ALIGN_RIGHT);
		
	}
	
	private class RegisterResponse implements AsyncCallback<Boolean> {
		@Override
		public void onFailure(Throwable caught) {
		}

		@Override
		public void onSuccess(Boolean result) {
			
			if (result.booleanValue()) {
				PanelHandler.showHome();
			} else {
				
			}
		}
	}
}
